package cn.edu.sjtu.se.dslab.component.dp.parse;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.edu.sjtu.se.dslab.component.design.DesignPatternType;
import cn.edu.sjtu.se.dslab.util.FileUtil;

public class DesignPatternInstanceXMLParser {
	
	private Document document;
	private DesignPatternInstanceBean dpiBean;
	private DesignPatternBean dpBean;
	
	public DesignPatternInstanceXMLParser(String path, DesignPatternBean dpBean, DesignPatternInstanceBean dpiBean) {
		this.dpiBean = dpiBean;
		SAXReader reader = new SAXReader();
		path = FileUtil.getRootPath() + path;
		try {
			document = reader.read(new File(path));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		this.dpBean = dpBean;
	}

	public DesignPatternInstanceBean parse(){
		if(document == null) {
			return dpiBean;
		}
		readDesignPatternInstance();
		return dpiBean;
	}

	private void readDesignPatternInstance() {
		Element rootElement = document.getRootElement();
		dpiBean.setName( rootElement.elementText( DesignPatternInstanceBean.NAME ) );
		String type = rootElement.elementText( DesignPatternInstanceBean.TYPE);
		//get the type according to the name
		dpiBean.setType( DesignPatternType.valueOf(type.toUpperCase()));
		dpiBean.setMaxId( Integer.parseInt( rootElement.elementText( DesignPatternInstanceBean.MAX_ID)));
		readInstances(rootElement.element(DesignPatternInstanceBean.INSTANCES));
	}

	private void readInstances(Element instances) {
		@SuppressWarnings("unchecked")
		List<Element> elements = instances.elements();
		for(Element element: elements){
			Map<String, Property> properties = readInstance(element);
			dpiBean.getInstances().add(properties);
		}
	}

	private Map<String, Property> readInstance(Element instance) {
		Map<String, Property> properties = new HashMap<String, Property>();
		@SuppressWarnings("unchecked")
		List<Element> elements = instance.elements();
		for(Element pElement: elements){
			Property p = readProperty(pElement);
			properties.put(p.getName(), p);
		}
		return properties;
	}
	
	private Property readProperty(Element pElement){
		String pName = pElement.elementText( Property.NAME_ATTR);
		Property p = (Property)dpBean.getPropertyByName(pName).clone();
		if (p != null) {
			p.setValue(pElement.elementText(Property.VALUE));
		}
		return p;
	}
	
}
